import 'dart:io';

import 'package:dio/dio.dart';
import 'package:dio/io.dart';

import '../../config/app_glabol.dart';
import '../../mode/base/base_data.dart';
import '../../router/app_routes_manager.dart';
import '../app_utils.dart';
import 'Interceptors.dart';
import 'http_ui_handle.dart';

/// 项目的http相关的配置信息
class HttpManager {
  static var BASE_URL = (AppUtils.isBeta || AppUtils.isDebug)
      ? "https://tapi-sip.510gow.com"
      : "https://api-sip.510gow.com";
  static const String BASE_PATH = "/interface?";
  static HttpManager? _instance;

  static HttpManager getInstance() {
    _instance ??= HttpManager._instance;
    return _instance!!;
  }

  // 私有构造函数
  HttpManager._internal() {
    createDio();
  }

  late Dio _dio;

  static Dio get dio => getInstance()._dio;

  Dio createDio() {
    if (_dio == null) {
      _dio = Dio(BaseOptions(
        contentType: 'application/json',
//      baseUrl: Config.BASE_URL,
      ));
      _dio.options.receiveTimeout = const Duration(seconds: 20);
      _dio.options.connectTimeout = const Duration(seconds: 20);
      _dio.options.sendTimeout = const Duration(seconds: 20);
      _dio.interceptors.add(DefaultInterceptor());
      if (AppGlabol.httpProxy.length > 5) {
        (_dio.httpClientAdapter as IOHttpClientAdapter).createHttpClient = () {
          return createProxyClient();
        };
      }
    }
    return _dio;
  }

  HttpClient createProxyClient() {
    final HttpClient client = HttpClient();
    client.findProxy = (Uri uri) {
      // 返回代理服务器地址
      return "PROXY ${AppGlabol.httpProxy}";
    };
    client.badCertificateCallback =
        (X509Certificate cert, String host, int port) => true; // 忽略 SSL 证书验证
    return client;
  }

  //处理逻辑
  static handleResult(
    HttpResponse data, {
    HttpUiHandle? handle,
  }) {
    if (data.isSuccess) {
      return;
    }
    if (data.code == -1 || data.code == -2) {
      AppRouterJump.login();
    } else {
      handle?.showErrorToast(data.code.toString());
    }
  }

  static void setHttpProxy(String host, String port) {
    if (host.isNotEmpty) {
      AppGlabol.httpProxy = host + ':' + port;
    } else {
      AppGlabol.httpProxy = '';
    }
    getInstance().createDio();
  }

  static Options checkOptions(String method, Options? options) {
    options ??= Options();
    options.method ??= method;
    return options;
  }

  //创建Url
  static String createUrl({String? path}) {
    return "${HttpManager.BASE_URL}${path ?? BASE_PATH}";
  }
}
